/*************************************************************************
    > File Name    : EventLoop.h
    > Author       : LiuLei
    > Mail         : 2261459486@qq.com 
    > Created Time : 2022年11月25日 星期五 12时10分15秒
 ************************************************************************/

#ifndef __LL_EVENTLOOP_H__
#define __LL_EVENTLOOP_H__

#include "MutexLock.h"
#include "RoundRobin.h"
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/timerfd.h>
#include <vector>
#include <map>
#include <memory>
#include <functional>
using std::vector;
using std::map;
using std::shared_ptr;
using std::function;

class Acceptor;
class TcpConnection;

using TcpConnectionPtr = shared_ptr<TcpConnection>;
using TcpConnectionCallback = function<void(const TcpConnectionPtr &ptr)>;
using Function = function<void()>;

class EventLoop
{
public:
    EventLoop(Acceptor &acceptor);
    ~EventLoop();
    
    void loop();
    void unloop();

    //设置回调函数
    void setConnectionCallback(TcpConnectionCallback &&cb);
    void setMessageCallback(TcpConnectionCallback &&cb);
    void setCloseCallback(TcpConnectionCallback &&cb);

    void runInLoop(Function &&cb);

private:
    void waitEpollFd();                             //调用epoll_wait函数，进行阻塞监听
    void handleNewConnection();                     //处理新的连接
    void handleMessage(int fd);                     //处理消息的发送

    int createEpollFd();                            //创建epfd
    void addEpollReadFd(int fd);                    //将fd添加到红黑树监听
    void deleteEpollReadFd(int fd);                 //从红黑树上取消监听

    int createEventFd();

    int createTimerFd();
    void setTimerFd(int initSec, int peridocSec);

    void handleRead();
    void handleTimerFd();

    void weakup();
    void doPendingFunctions();

private:
    int                             _epfd;          //红黑树的根节点
    int                             _evfd;          //eventfd的返回值
    int                             _timerfd;       //timerfd的返回值
    
    bool                            _isLooping;     //循环的标志位
    
    vector<struct epoll_event>      _evtList;       //存储满足条件的事件
    map<int, TcpConnectionPtr>      _conns;         //键值对
    vector<Function>                _pendings;

    Acceptor                        &_acceptor;
    MutexLock                       _mutex;
    RoundRobin                      _roundRobin;

    //三个事件的回调函数
    TcpConnectionCallback           _onConnection;
    TcpConnectionCallback           _onMessage;
    TcpConnectionCallback           _onClose;
};

#endif
